package com.gaoyi.websocket.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.Objects;

@Configuration
@Slf4j
public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator {

    /**修改握手时的操作*/
    @Override
    public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {

        HttpSession httpSession=(HttpSession) request.getHttpSession();
        if (Objects.isNull(httpSession)){
            log.error("httpSession为空, header = [{}]", request.getHeaders());
        }
        log.debug("webSocket握手, sessionId = [{}]", httpSession.getId());

        /**这里是放到 config中 */

        config.getUserProperties().put("sessionId", httpSession);
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}
